package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.AlertDataHandleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.User;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.service.AlertDataService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.AlertDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AlertDataServiceImpl implements AlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    @Override
    public PageResponse<AlertDataVo> pageQuery(Integer pageNum, Integer pageSize, String deviceName, Long endTime, Long startTime, Integer id, Integer status) {
        PageHelper.startPage(pageNum, pageSize);

        Page<AlertData> list = alertDataMapper.selectListByConditions(deviceName, endTime == null ? null : LocalDateTimeUtil.of(endTime), startTime == null ? null : LocalDateTimeUtil.of(startTime), id, status);
        return PageResponse.of(list, AlertDataVo.class);
    }

    @Override
    public void handleAlertData(Long id, AlertDataHandleDto alertDataHandleDto) {
        AlertData alertData = BeanUtil.toBean(alertDataHandleDto, AlertData.class);
        String subject = UserThreadLocal.getSubject();
        if (StrUtil.isNotEmpty(subject)) {
            User user = JSONUtil.toBean(subject, User.class);
            alertData.setProcessorId(user.getId());
            alertData.setProcessorName(user.getNickName());
        }
        alertData.setId(id);
        alertData.setStatus(1);
        alertDataMapper.updateByPrimaryKeySelective(alertData);
    }
}
